package com.meizu.control;

import com.alibaba.fastjson.JSONObject;
import com.meizu.entity.Cart;
import com.meizu.entity.Photo;
import com.meizu.entity.User;
import com.meizu.service.CartService;
import com.meizu.service.PhotoService;
import com.meizu.utils.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  购物车的控制层操作类
 * @author hxf
 * @date 2023/3/28
 **/
@WebServlet("/cart")
public class CartServlet extends BaseServlet {
    CartService cs = new CartService();
    PhotoService ps = new PhotoService();
    @Override
    public String excute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Object user = session.getAttribute("user");
        if(user instanceof User) {//判断用户是否登录状态
            User u = (User) user;
            Integer uid = u.getUid();
            List<Cart> carts = cs.selectByUid(uid);//指定用户的购车
            Integer s=0;//商品数量
            if (carts!=null){
                s=carts.stream ().collect(Collectors.summingInt(Cart::getCount));
            }
            Integer total = 0;
            for (int i = 0; i < carts.size(); i++) {
                total += carts.get(i).getDprice()*carts.get(i).getCount();
            }
            session.setAttribute("carts", carts);//指定用户的购车商品集合
            session.setAttribute("s",s);         //总数量
            session.setAttribute("total",total); //合计，指定用户的购车商品总价格
            return "f:cart";//显示购物车
        }else {//没有登录重定向到登录页
            return "r:index";
        }
    }

    /**
     *加入购车，插入
     */
    public String insertCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String Count = request.getParameter("gcount");
        Integer count = Integer.parseInt(Count);//数量
        Object Did = session.getAttribute("did");
        Integer did = (Integer) Did;            //详情id
        Object user = session.getAttribute("user");
        User u = (User) user;
        Integer uid = u.getUid();               //用户id
        List<Cart> carts = cs.selectByUid(uid);
        JSONObject json = new JSONObject();
        Boolean flag = true;
        for (int i = 0; i < carts.size(); i++) {
            if(carts.get(i).getDid()==did){//购物车存在该商品，数量进行修改
                Integer c = count+carts.get(i).getCount();//原数量与现在加入的数量相加
                Integer r = cs.updateCount(c, uid, did);//执行修改
                json.put("r",r);
                flag=false;
                break;
            }
        }
        if(flag) {//购物车没有该商品，插入新的
            List<Photo> photos = ps.selectPhoto(did);
            String cphoto = photos.get(0).getPhoto();//商品图片（该详情id关联图片表的第一张图片）
            cs.doUpId();//让主键自增连续
            Integer r = cs.InsertCart(did, uid, cphoto, count);//执行插入
            json.put("r", r);
            flag=true;
        }
        List<Cart> cart = cs.selectByUid(uid);//点击”加入购物车“，新增后的购物车商品集合
        Integer s=0;//商品数量
        if (cart!=null){
            for (int i = 0; i < cart.size(); i++) {
                s+= cart.get(i).getCount();
            }
        }
        System.out.println("s:"+s);
        json.put("s",s);//商品总数量
        return json.toJSONString();
    }

    /**
     *删除单个商品
     */
    public JSONObject deleteCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType ("application/json;charset=utf-8");
        String id=request.getParameter ("cid");
        Integer cid=Integer.valueOf (id);
        Integer i=cs.deleteCartByCid (cid);//删除指定cid的商品
        User user=(User)session.getAttribute ("user");
        List<Cart> cartList=null;
        Integer s=0;//商品数量
        cartList=cs.selectByUid(user.getUid());
        if (cartList!=null){
            s=cartList.stream ().collect(Collectors.summingInt(Cart::getCount));
        }
        JSONObject json=new JSONObject ();
        json.put ("cartList",cartList);
        json.put ("s",s);
        return json;
    }

    /**
     *批量删除/全部删除
     */
    public JSONObject deleteCarts(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType ("application/json;charset=utf-8");
        String[] cid=request.getParameterValues ("cids");
        for (String c : cid) {//循环删除指定cid的商品
            Integer i = cs.deleteCartByCid (Integer.parseInt(c));
        }
        User user=(User)session.getAttribute ("user");
        List<Cart> cartList=null;
        Integer s=0;//商品数量
        cartList=cs.selectByUid(user.getUid());
        if (cartList!=null){
            s=cartList.stream ().collect(Collectors.summingInt(Cart::getCount));
        }
        JSONObject json=new JSONObject ();
        json.put ("cartList",cartList);
        json.put ("s",s);           //数量
        return json;
    }

    /**
     *商品数量修改
     */
    public String updateCartCount(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer count = Integer.valueOf(request.getParameter("count"));
        Integer cid = Integer.valueOf(request.getParameter("cid"));
        Integer r = cs.changeCount(count, cid);
        JSONObject json = new JSONObject();
        json.put("r",r);
        return json.toJSONString();
    }
}
